<!-- 商品详情页 -->
<template>
	<view class="">
		<view class="goods-box" :class="isShowPopup ? 'popup-show': ''">
			<view class="nav pf x-c" :style="{paddingTop:`${systemInfo.safeArea.top}px `}">
				<view class="back pa x-f" @tap.stop="back()">
					<image :src="back_img" />
				</view>
				<view class="top_btn">
					<view class="anchor_button x-f" :style="{'top':menuButtonInfo.top + 'px'}">
						<view class="left tc" @tap="roll(true)" :class="{'gray' : change_style}">商品</view>
						<view class="right tc" @tap="goDetail" :class="{'gray' : !change_style}">详情</view>
					</view>
				</view>
			</view>
			<!-- 轮播图 -->
			<view class="banner">
				<banner-list :banners="goods.imgs" :heightFix="true" background="#FFF" swiperHeight="630rpx">
				</banner-list>
			</view>
			<view class="money x-bc pr">
				<view class="x-f">
					<view class="score" v-if="goods.is_group">{{goods.group_points || 0}}积分</view>
                    <view class="score" v-else>{{goods.points || 0}}积分</view>
					<view class="line_score" v-if="goods.is_group">{{goods.points || 0}}积分</view>
				</view>
				<view class="right">
					<view class="count_down" v-if="goods.is_group == 1">
						<view class="text">倒计时：</view>
						<u-count-down :timestamp="downTime" :separator="zh" color="#E93323" font-size="22" height="36"
							separatorSize="22" separatorColor="#FFF"></u-count-down>
					</view>
					<view class="exchange" v-if="goods.is_group">已拼{{saleNum}}份</view>
				</view>
			</view>
			<view class="title pr">
				<view class="goods-title">{{goods.spu_name}}</view>
				<view class="goods-desc">{{goods.simple_desc}}</view>
			</view>
			<!-- 拼团 -->
			<groupop 
				:isShowPopup="isShowPopup"
                :group="goodsItem" 
                :groupList="goodsList" 
				@go_close="go_close"
                @popup="popup" 
				@openGroups="openGroups"
                @popups="popups"
                v-if="goodsItem.length >= 1 && goods.is_group == 1"></groupop>
			
			<view class="advert_box" id="goodDetail">
				<view class="advert" v-for="(item, index) in goods.detail_html" :key="index">
					<view class="">
						<image class="detailimg" :src="item" mode="widthFix"></image>
					</view>
				</view>
			</view>
            <!-- 切换 -->
            <view class="tabs" v-if="guessGoods.length">
            	<tabbar :tab="tab" :active="active" :showLabel="false" @change_status="change_status"
            		:paddingTop="true">
            	</tabbar>
            	<view class="goods-box x-bc">
            		<template>
            			<view class="goods  pr" v-for="(item, index) in guessGoods" :key="index" v-if="index < 6" @click="jumpDetail(item)">
            				<image :src="item.list_pic_url"></image>
							<view class="team x-c pa" v-if="item.is_group">拼团</view>
            				<view class="goodsText">
            					<view class="label">{{item.spu_name}}</view>
            					<view class="value">{{item.points}}积分</view>
            				</view>
            			</view>
            		</template>
            	</view>
            </view>
			<bottom :height="80" ref="bottomChild" @open="open" @jumpCart="jumpCart" @myTeam="myTeam" :mobile="phone"
				@getCollect="getCollect" :bottom="bottom" :isCollection="isCollection" :show_group="goods.is_group"
				@exchange="exchange"></bottom>

		</view>
		<specificationPopup ref="speciChild" @summitInfo="summitInfo" :goods='goods' :platform="platform" :isShowBtn="isShowBtn"
			 @getMoney="getMoney" @closeNorms="closeNorms" @getNorm="getNorm"></specificationPopup>
	</view>

</template>

<script>
	import {
		mapState
	} from 'vuex';
	import mixins from '@/common/mixins.js';
	import bottom from '../components/bottom.vue'
	import groupop from '../components/group.vue'
	import specificationPopup from '../components/specification-popup.vue'
	export default {
		mixins: [mixins],
		components: {
			bottom,
			groupop,
			specificationPopup
		},
		onReady: function() {
			let that = this
			that.$tools.getDom('.advert').exec(function(data) {
				that.distance_from_top = data[0].top - that.statusBarHeight - that.navHeight
				that.distance_from_bottom = data[0].bottom
			})
		},
		data() {
			return {
				downTime: 0,			 // 倒计时
				isShowPopup: false, 	 // css控制底层不允许滚动
				isCollection: 0,		 // 收藏
				bottom: [{   			 // 底部按钮
					img: this.imgUrl + "enshrine.png",
					select: '/static/image/selectCollect.png',
					title: "收藏"
				}, {
					img: this.imgUrl + "service.png",
					title: "联系客服"
				}],
				change_style: true, 	 //顶部商品/详情切换按钮
				watchScroll: true, 		 // 是否监听滚动
				distance_from_top: 0,	 // 详情距离顶部距离
				distance_from_bottom: 0, // 详情距离底部距离
				onoff: true,   			 // 解决防抖
				statusBarHeight: getApp().globalData.statusBarHeight,   // 状态栏的高度
				navHeight: getApp().globalData.navHeight, 			    // 导航栏的高度
				capHeight: getApp().globalData.capHeight, 				// 胶囊的高度
				winHeight: getApp().globalData.winHeight,				// 屏幕高度
				active: 0,												// 下标
				group: [],												// 组，藐视无用
				back_img: this.imgUrl + 'back.png',						// 返回图标
				showNorms: false, 										// 显示规格
				postCart: { 											// 提交购物车
					member_id: 1,
					spu_id: '',
					sku_id: '',
					sale_count: 1,
					consume_amount: 0,
					consume_points: 0,
				},
				Info: [], 												// 商品详情
				money: 0,												// 金额
				sumTotal: {}, 											// 消费总数
				sku_id: '',                                             // 规格id
				isShowBtn: 0, 											// 0购物车，1立即兑换，2发起拼团
				sku: null,												// 规格
				goodsItem: {},											// 商品信息	
                goodsList: {}, 											// 传递给子组件的数据
				platform: 'ios', 										// 手机系统
				guessGoods: [], 										// 猜你喜欢
				detailHeigt: 0, 										// 商品详情高度
				obj: {          										// 猜你喜欢
					page: 1,
					pagesize: 6,
					category_id: '',
					orderby_type: 'number',
					orderby: 'desc',
					lat: '24.881627',
					lng: '118.628881',
					member_id: 1
				},
				love: [],      											// 猜你喜欢
				goodsHot: [],  											// 热门商品
				points: 0,  											// 积分
				group_points: 0, 										// 团购积分
				phone: 0, 												// 电话
			}
		},
		computed: {
			...mapState({
				getId: state => state.goods.detail,           // 获取商品信息
				tab: state => state.goods.tabs,				  // 商品tab标签
				systemInfo: state => state.init.systemInfo,   // 设备信息
				collectList: state => state.user.collect, 	  // 个人收藏信息
				goods: state => state.goods.goodsInfo,		  // 商品信息
				groupList: state => state.goods.groupList, 	  // 拼团列表
                menuButtonInfo: state => state.init.menuButtonInfo, // 获取胶囊高度
                userPoints: state => state.init.points,       // 用户剩余积分
                saleNum: state => state.goods.saleNum,    	  // 用户剩余积分
			})
		},
		onLoad() {
			// 获取当前时间
			let timestamp = new Date().getTime();
			// 获取分钟到秒
			timestamp = parseInt(timestamp/1000) 
			this.downTime = this.goods.group_end_time -timestamp
			this.phone = this.goods.mobile
			// 判断是否拼团
			if(this.goods.is_group) {
				this.get_groupList();
			}
			this.isCollection = this.goods.isCollection
			this.platform = this.systemInfo.platform
			this.guessGoods = this.love
			// 获取元素高度
			const query = uni.createSelectorQuery().in(this);
			query.select('#goodDetail').boundingClientRect(data => {
				this.detailHeigt = data.top - 50;
			}).exec();
			// 获取商品详情分类id
			let str = this.goods.category_path_id.replace(/\//g, "");
			this.obj.category_id = str
			// 获取商品猜你喜欢
			this.$api('giftpage',this.obj).then( res => {
				let arr = res;
				this.love = arr.data.data;
				this.guessGoods = arr.data.data;
			})
			// 24小时热销
			this.obj.orderby_type = 'number';
			this.obj.orderby = 'asc';
			this.$api('giftpage',this.obj).then( res => {
				let arr = res
				this.goodsHot = arr.data.data
			})
			this.points = this.goods.points
			this.group_points = this.goods.group_points
		},
		onShow() {
			// 当页面显示时清空规格参数
			this.sku = null;
		},
		onUnload() {
			// 清除总积分
			this.$store.dispatch('cart/get_sum', 0)
			// 清除总金额
			this.$store.dispatch('cart/get_money', 0)
			// 清除已选择数量
			this.$store.dispatch('cart/get_count', 0)
		},
		methods: {
			// 打开团购组件
			openGroups() {
				this.isShowPopup =true;
			},
            // 子组件传递的事件
            popup() {
                // 打开规格选择器;
                this.$refs.speciChild._data.showNorms = true;
                // 需要告诉选择器的按钮，这是需要加入拼团;
                this.isShowBtn = 2;
                this.type = 'group';
                this.$store.dispatch('order/get_type', this.type);
            },
			// 子组件
			go_close() {
				this.isShowPopup = false;
			},
            // 子组件传递的事件
            popups() {
                this.$refs.speciChild._data.showNorms = true;
                this.isShowBtn = 2;
                this.type = 'group';
                this.$store.dispatch('order/get_type', this.type);
            },
			// 跳转商品详情
			jumpDetail(item) {
				let obj = {
					"spu_id": item.spu_id,
					"sku_id": item.sku_id,
				}
				this.$api('giftinfo',obj).then(res => {
					let goods = res.data;
				    this.$store.dispatch('goods/get_goodsInfo',goods)
				})
				this.$store.dispatch('goods/get_detail',item)
				this.$Router.push({
				    path: '/pages/goods/detail/index',
					params: 'params'
				})
			},
			// 跳转商品详情位置
			goDetail() {
				// 设置当前距离顶部距离为0；
				uni.pageScrollTo({
					duration: 500, // 毫秒
					scrollTop: this.detailHeigt // 位置
				});
			},
			closeNorms() {
				this.isShowPopup = false // css控制底层不允许滚动
			},
			// 获取拼团列表
			get_groupList() {
				let obj = {
					page: 1,
					pagesize: 10000,
					spu_id: this.goods.spu_id
				}
				let time = new Date() / 1000;
				this.$store.dispatch('goods/get_groupList', obj).then(res => {
					this.goodsItem = res.data;
                    this.goodsList = this.goodsItem.slice(0, 2);
					for (let i in this.goodsItem) {
						this.goodsItem[i].endTime = this.goodsItem[i].validity_time - time;
					}
				});

			},
			// 发起拼团
			myTeam() {
				this.goods.points = this.group_points
				this.$refs.speciChild._data.points = this.group_points
				this.type = 'group';
				this.$store.dispatch('order/get_type', this.type);
				this.isShowBtn = 2;
				this.$refs.speciChild._data.goods = this.goods;
				this.$refs.speciChild._data.showNorms = true;
				this.showNorms = true;
				this.isShowPopup = true;
			},
			// 获取规格
			getNorm(val) {
				this.sku = val
				// 如果规格不为空
				if(this.sku != null) {
					if(this.type == 'group') {
						if (this.goods.is_group) {
							this.goods.points = val.group_points
							this.$refs.speciChild._data.points = val.group_points
						} else {
							this.goods.points = val.points
							this.$refs.speciChild._data.points = val.points
						}
					}
					if(this.type == 'cart') {
						this.goods.points = val.points
						this.$refs.speciChild._data.points = val.points
					}
					if(this.type == 'exchange') {
						this.goods.points = val.points
						this.$refs.speciChild._data.points = val.points
					}
				}
			},
			// 积分抵扣剩余金额
			getMoney(val) {
				this.sumTotal.money = val.money;
				this.sumTotal.points = val.points;
			},
			// 请求商品详情
			getInfo() {
				let obj = {
					"spu_id": this.getId.spu_id,
					"sku_id": this.getId.sku_id,
				}
				this.$api('giftinfo', obj).then(res => {
					let arr = res
					let newArr = arr.data;
					this.isCollection = arr.data.isCollection
					this.$store.dispatch('goods/get_goodsInfo', newArr)
				})
			},
			// 确定信息
			summitInfo(val) {
				val.points = Number(val.points)
				val.money = Number(val.money)
				let moneyTol = val.money
				let pointsTol = val.points
				let money = (val.money/val.num).toFixed(2)
				let points = (val.points/val.num).toFixed(0)
				let is = false; // 跳转订单
				// 判断规格是否为空
				if(this.sku != null) {
					this.postCart.spu_id = this.sku.spu_id
					this.postCart.sku_id = this.sku.sku_id
				}
				if (this.sku == null) {
					this.$tools.toast('商品规格不能为空')
				} else {
					this.isShowPopup = false;
					this.postCart.sale_count = val.num
					this.postCart.consume_points = Number(this.sumTotal.points)
					this.postCart.consume_amount = Number(this.sumTotal.money)
					// // 加入购物车
					if (this.isShowBtn == 0) {
						this.postCart.consume_points = Number(pointsTol)
						this.postCart.consume_amount = Number(moneyTol)
						this.postCart.unit_points = Number(points)
						this.postCart.unit_amount = Number(money)
						this.$api('memberhandleCart', this.postCart).then(res => {
							let arr = res.data
							this.$refs.speciChild._data.showNorms = false;
							if (res.status) {
								this.$tools.toast('添加购物车成功')
								// 将规格清空
								this.sku = null
								// 存一下信息
								this.$store.dispatch('cart/get_cart_group');
							}
							this.$refs.speciChild._data.selectAct = -1;
						})
					}
					// 立即兑换
					if (this.isShowBtn == 1) {
                        let order = [];
                        let obj = {};
                        is = true;
                        // 构造信息
                        obj.pic_url = this.goods.pic_url0;
                        obj.spu_name = this.goods.spu_name;
                        obj.display_string = this.sku.display_string;
						obj.points = this.sku.points;
                        obj.sale_count = val.num;
                        obj.consume_points =  pointsTol;
                        obj.consume_amount = moneyTol;
						obj.unit_points = pointsTol
						obj.unit_amount = moneyTol
                        obj.sku_id = this.sku.sku_id;
                        obj.is_group = this.goods.is_group;
                        order.push(obj);
						this.$store.dispatch('order/get_group', order);
						this.$store.dispatch('cart/get_money', moneyTol);
						this.$store.dispatch('cart/get_sum', pointsTol);
						this.$store.dispatch('order/get_sumInit', pointsTol);
						// 查询可用优惠券
						this.$api('ordercoupon', {
							shop_id: this.goods.shop_id,
							max_points: this.goods.points
						}).then(res => {
							let arr = res
							arr.data.map(item => {
								item.flag = false;
								item.use_end_time = this.time_data(item.use_end_time, 'f_date');
								item.use_start_time = this.time_data(item.use_start_time, 'f_date');
							})
							this.$store.dispatch('order/get_canUser', arr.data)
							this.$refs.speciChild._data.showNorms = false;
							this.$refs.speciChild._data.selectAct = -1;
						})
					}
					// 发起拼团
					if (this.isShowBtn == 2) {
                        // 计算拼团所需积分
                        let score = this.postCart.consume_points * val.num;
                        if (this.userPoints < score) {
                            this.$tools.toast('积分不足');
                            return;
                        };
                        let order = [];
                        let obj = {};
                        is = true;
                        // 构造信息
                        obj.pic_url = this.goods.pic_url0;
                        obj.spu_name = this.goods.spu_name;
                        obj.display_string = this.sku.display_string;
                        obj.points = pointsTol;
                        obj.sale_count = val.num;
                        obj.consume_points = pointsTol;
                        obj.consume_amount = 0;
                        obj.sku_id = this.sku.sku_id;
						obj.is_group = this.goods.is_group;
						obj.unit_points = pointsTol
						obj.unit_amount = moneyTol
                        order.push(obj);
						order[0].consume_points = pointsTol;
						this.postCart.consume_points = pointsTol;
						this.$store.dispatch('order/get_group', order);
						this.$store.dispatch('cart/get_money', 0);
						this.$store.dispatch('cart/get_sum', pointsTol);
						this.$store.dispatch('order/get_sumInit', pointsTol);
						// 查询可用优惠券
						this.$api('ordercoupon', {
							shop_id: this.goods.shop_id,
							max_points: this.goods.points
						}).then(res => {
							let arr = res
							arr.data.map(item => {
								item.flag = false;
								item.use_end_time = this.time_data(item.use_end_time, 'f_date');
								item.use_start_time = this.time_data(item.use_start_time, 'f_date');
							})
							this.$store.dispatch('order/get_canUser', arr.data)
							this.$refs.speciChild._data.showNorms = false;
							this.$refs.speciChild._data.selectAct = -1;
						})
					}
				}
				if (is) {
					this.$Router.push({
						path: '/pages/order/index'
					})
				}
			},
			//加入购物车
			jumpCart() {
				this.goods.points = this.points
				this.$refs.speciChild._data.points = this.points
				this.type = 'cart';
				this.$store.dispatch('order/get_type', this.type);
				this.isShowBtn = 0
				this.$refs.speciChild._data.goods = this.goods
				this.$refs.speciChild._data.showNorms = true
				this.showNorms = true
				this.isShowPopup = true
			},
			// 收藏
			getCollect() {
				let obj = {
					"member_id": 1,
					"spu_id": this.getId.spu_id
				}
				if (this.goods.isCollection) {
					this.$api('giftcollection', obj).then(res => {
						if(res.status) {
							this.$store.dispatch('user/get_collect', this.goods)
							setTimeout(()=> {
								this.getInfo()
								this.$tools.toast('取消收藏成功')
							},300)
						}
					})
				} else {
					this.$api('giftcollection', obj).then(res => {
						if(res.status) {
							this.$store.dispatch('user/get_collect', this.goods)
							setTimeout(()=> {
								this.getInfo()
								this.$tools.toast('收藏成功')
							},300)
						}
					})
				}
			},
			//立即兑换
			exchange() {
				this.goods.points = this.points
				this.$refs.speciChild._data.points = this.points
				this.type = 'exchange';
				this.$store.dispatch('order/get_type', this.type);
				this.isShowBtn = 1
				this.isShowPopup = true
				this.$refs.speciChild._data.goods = this.goods
				this.$refs.speciChild.isShow = true;
				this.$refs.speciChild._data.showNorms = true
			},
			// 商品标签切换
			change_status(index) {
				this.active = index
				if (this.active == 1) {
					this.guessGoods = this.goodsHot
				}
				if (this.active == 0) {
					this.guessGoods = this.love
				}
			},
			back() {
				this.$Router.back(1);
			},
			jump(path, params) {
				this.$Router.push({
					path: path,
					params: params
				})
			},
			open() {
				this.$refs.popups.$data.show = true;
			},
			// 拼团弹窗
			go_exchage() {
				this.$refs.popup.$data.show = true;
			},
			// 滚动到指定位置
			roll(type) {
				var that = this
				var fun = function() {
					that.change_style = type
					if (that.change_style) {
						uni.pageScrollTo({
							scrollTop: 0,
							duration: 200
						})
					} else {
						uni.pageScrollTo({
							scrollTop: that.distance_from_top,
							duration: 500
						})
					}
					that.watchScroll = false
					setTimeout(() => {
						that.watchScroll = true
					}, 300)
				}


				// 防止快速点击
				if (this.onoff) {
					this.onoff = false
					fun()
					setTimeout(() => {
						this.onoff = true
					}, 300)
				} else {
					// // console.log("请稍后点击")
				}
			},
		},
		onPageScroll: function(e) {
			let that = this
			if (!that.watchScroll) {
				return;
			}
			if (e.scrollTop < that.distance_from_top && this.distance_from_bottom >= this.winHeight) {
				that.change_style = true
			} else {
				that.change_style = false
			}
			if (e.scrollTop < 50) {
				that.change_style = true
			}
		},

	}
</script>

<style lang="scss" scoped>
	@import './index.scss';

	.popup-show {
		overflow: hidden;
		position: fixed;
		height: 100%;
		width: 100%;
	}
</style>
